package org.songtang.springbootexcel.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class ExcelController {

    @GetMapping("/download/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        try (InputStream inputStream = new ClassPathResource("templates/multiSelect.xlsm").getInputStream()) {
            // 动态下拉数据
            List<String> orgNameList = Arrays.asList("组1","组2");


            // 设置响应头
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            String format = DateUtil.format(new Date(), "yyyyMMddHHmmss");
            String fileName = URLEncoder.encode("test"+ format, "UTF-8");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName + ".xlsm");

            // 创建 ExcelWriter 并设置 SpinnerWriteHandler
            ExcelWriterBuilder writerBuilder = EasyExcel.write(response.getOutputStream())
                    .withTemplate(inputStream);

            // 写入空数据以应用模板和处理器
            try (ExcelWriter excelWriter = writerBuilder.build()) {
                // 写入第二个 Sheet，将 orgNameList 写入第一列
                WriteSheet secondSheet = EasyExcel.writerSheet(1).build();
                List<List<String>> data = orgNameList.stream()
                        .map(name -> {
                            List<String> row = new ArrayList<>();
                            row.add(name);
                            return row;
                        })
                        .collect(Collectors.toList());
                excelWriter.write(data, secondSheet);

                // 写入第一个 Sheet
                WriteSheet firstSheet = EasyExcel.writerSheet(0).build();
                excelWriter.write(new ArrayList<>(), firstSheet); // 提供一个空列表以避免歧义
            }

        } catch (IOException e) {
            throw new RuntimeException("Failed to download the template", e);
        }
    }
}
